import { PlatformConfig } from '/@/model';
import { PLATFORM_CONFIG_KEY, TENANT_CONFIG_KEY, TENANT_INIT_ERROR_KEY, LAST_TENANT_ID } from '/@/enums/cacheEnum';
import { getCacheByDynKey, setCacheByDynKey} from '/@/utils/cache/index'
import { useMessage } from '/@/hooks/web/useMessage';
import { ConfigKey } from '/@/views/system/config/config.model';
import { getAppInitConfig } from '/@/views/system/config/config.api';
import { useGlobSetting } from '/@/hooks/setting';
import { getUrlParam } from '../utils'
import { TenantType } from '/@/enums/bizEnum'
import * as authCache from '/@/utils/cache/module';
const glob = useGlobSetting();

/**
 * 租户解析结果
 */
export interface TenantParseResp {
  // 租户id
  id?: string;
  // 只有两种情况 site/s{xx} 或者 admin(id = 1)
  baseUrl?: string;
}


enum SiteUrlPre {
  SITE = 'site',
}

/**
 * 不用取redirect中的tenantId, 因为跳转到登录页面后, 只需要获取在代码中配置的租户id, 登录页面一般由平台提供
 * 不需要为每个租户设置
 */
export const getTenantId = () => {
  const href = decodeURIComponent(window.location.href)
  // const path = href.includes('redirect') ? href.substring(href.indexOf('redirect=')).replace('redirect=', '') : href
  return getUrlParam('tenantId', href) || authCache.getSelectTenant()?.id || useGlobSetting().platformTenantId
}

export const getAppIdId = () => {
  const href = decodeURIComponent(window.location.href)
  // const path = href.includes('redirect') ? href.substring(href.indexOf('redirect=')).replace('redirect=', '') : href
  return getUrlParam('appId', href) || useGlobSetting().platformTenantId
}

export const addWorkspaceParamsToUrl = (url? : string) => {
  if (!url) {
    return `tenantId=${getTenantId()}&appId=${getAppIdId()}`;
  }
  if (url.indexOf('?') === 0) {
    return `${url}?tenantId=${getTenantId()}&appId=${getAppIdId()}`
  }

  // 创建一个包含查询字符串的对象
  const params = new URLSearchParams(url.split('?')[1]);

  // 将指定的参数移到最前边
  params.delete('tenantId');
  params.delete('appId');
  params.set('tenantId', getTenantId());
  params.set('appId', getAppIdId());

  // 将重新排序后的参数组合成新的 URL
  return `${url.split('?')[0]}?${params.toString()}`;
}

export const setLastTenantId = (tenantId: any) => {
  if (tenantId) {
    setCacheByDynKey(LAST_TENANT_ID, tenantId);
  }
}

/**
 * 检查租户的错误信息
 */
export const checkWebSiteError = () => {
  const { createMessage } = useMessage()
  const errorInfo = getCacheByDynKey(TENANT_INIT_ERROR_KEY)
  if (errorInfo) {
    // setCacheByDynKey(TENANT_INIT_ERROR_KEY, '');
    // createMessage.error('未知租户')
    // throw new Error('未知租户')
  }
}

export const getSiteBaseUrl = (tenantId) => {
  if (tenantId && tenantId !== '') {
    return `/${SiteUrlPre.SITE}/${tenantId}` 
  }
  return ''
}

// /**
//  * 获取租户id, 如果是admin, 则租户id为1
//  */
// export const parseTenantUrl = () : TenantParseResp => {
 
//   const resp : TenantParseResp = {
//     id: '-1',
//     baseUrl: ''
//   }
//   const path = window.location.pathname
//   console.log("path: ", path);
//   const tenantUrlPre = path.split('\/')[1] //

//   const tenantId = path.split('\/')[2]
//   console.log('tenantId: ', tenantId)
//   // 验证是否以site开头, 且其余为数字
//   if (tenantUrlPre && tenantUrlPre.startsWith(SiteUrlPre.SITE) && !isNaN(Number(tenantId))) {
//     resp.id = tenantId.replace('s', '')
//     resp.baseUrl = getSiteBaseUrl(tenantId)
//   }
//   console.log("tenantInfo: ", resp);
//   const tenantConfig : any = getCacheByDynKey<PlatformConfig>(PLATFORM_CONFIG_KEY) || {}
//   tenantConfig.tenantId = resp.id
//   setCacheByDynKey(PLATFORM_CONFIG_KEY, tenantConfig);

//   return resp
// }

export const getIntoPageTenantId = () : string => {
  const key = 'into_page_tenant_id'
  // TODO 后期如果需要为每个租户设置不同的登录页面, 可以按照如下顺序获取进入页面id
  // 1. 解析url上携带的租户id (如果有, 就覆盖缓存)
  // 2. 使用缓存中的租户id
  // 3. 缓存中没有, 使用平台配置的租户id (如果有, 就覆盖缓存)
  let intoPageTenantId : any = getCacheByDynKey<string>(key)
  if (!intoPageTenantId) {
    intoPageTenantId = glob.platformTenantId
    setCacheByDynKey(key, intoPageTenantId)
    console.log('intoPageTenantId', intoPageTenantId)
    return intoPageTenantId
  }
  console.log('intoPageTenantId', intoPageTenantId)
  return intoPageTenantId
}

export const isManageOrPlatform = (userStore : any) => {
  return userStore.getSelectTenant.tenantType === TenantType.MANAGE || userStore.getSelectTenant.tenantType === TenantType.PLATFORM
}
